package com.example.pdfandword.util;

import com.bfd.facade.MerchantServer;
import com.bfd.util.HttpConnectionManager4;
import com.bfd.util.MD5Utils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class StrategyApi {
    /**
     * 导出pdf单子
     */
    @Value(value = "${contract.path}")
    private static String uploadpath;


    public static String getBrData(String jsonData,String tokenidin,String apiCode){
        String res = "";
        try {
            MerchantServer ms = new MerchantServer();

            res = ms.getApiData(jsonData, apiCode);
            if(StringUtils.isNotBlank(res)){
                JSONObject json = JSONObject.fromObject(res);
                if(json.containsKey("code")&&json.getString("code").equals("100007")){
                    jsonData = JSONObject.fromObject(jsonData).put("tokenid", tokenidin).toString();
                    res = ms.getApiData(jsonData,apiCode);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return res;
    }

    public static void main(String[] args) {
        JSONObject jso = new JSONObject();
        JSONObject reqData = new JSONObject();
			/*
			 * #验证生产API
				verificationApi=https://api.100credit.cn/infoverify/v1/info_verify
				#验证测试Api
				SandboxverApi=https://sandbox-api.100credit.cn/infoverify/v1/info_verify
			 */
        jso.put("apiName", "SandboxverApi");//验证

			/*
			 * #贷前正式API------------------------------------------------------------------
				strategyApi=https://api.100credit.cn/strategyApi/v1/hxQuery
				#贷前测试API
				SandboxstrategyApi=https://sandbox-api.100credit.cn/strategyApi/v1/hxQuery
			 */
        //jso.put("apiName", "strategyApi");//贷前
//        jso.put("tokenid", StrategyApi.getTokenid());
        reqData.put("conf_id","MCP0031592");//验证策略编号
        //reqData.put("strategy_id", "STR0031593");//贷前策略编号
        reqData.put("id","140502198811102244");
        reqData.put("cell", "13986671118");
        reqData.put("name","王亮");
        jso.put("reqData", reqData);
//        String result = getBrData(jso.toString());
//        System.out.println(result);

//        String apiCode = "";
//        String userName = "";
//        String password = "";
//        String swift_number = "";
//        String orderno = "";
//        try {
//            String filePath =  ResourceUtil.getConfigByName("webUploadpath") + File.separator+orderno+File.separator+swift_number.toString()+ UUID.randomUUID().toString()+".pdf";
//            String tokenid = generateTokenid(apiCode,userName,password);
//            System.out.println("查询结果 : "+tokenid);
//
//            String result = downloadPdf(apiCode, tokenid, swift_number,filePath);
//                /*String result = getData(apiCode, tokenid);
//                System.out.printlwn("查询结果 : \n"+result);*/
//            System.out.println("查询结果 : \n"+result);
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }
    public static String getpdfbg(   String swift_number,
                                     String userNameinput,
                                     String pwdinput,
                                     String apiCodeinput){
        String filepathpdf = "orderno"+File.separator+swift_number.toString()+ UUID.randomUUID().toString()+".pdf";
        try {
            String filePath =  uploadpath + File.separator+filepathpdf;
            String tokenid = generateTokenid(apiCodeinput,userNameinput,pwdinput);
            System.out.println("查询结果 : "+tokenid);
            String result = downloadPdf(apiCodeinput, tokenid, swift_number,filePath);
            System.out.println("查询结果 : \n"+result);
        }catch (Exception e){
//            e.printStackTrace();
        }
        return  filepathpdf;
    }

    public static String getverfiresult( String idCard,String name,String bankId,String mobile,
                                         String userNameinput,String pwdinput,String apiCodeinput,
                                         String confId,String apiName,String LoginApi){
        String result="";
        JSONObject jso = new JSONObject();
        JSONObject reqData = new JSONObject();
        //获取 登陆验证码，1个小时内使用过，持续有效。
        MerchantServer ms = new MerchantServer();
        String tokenid = "";
        String login_res_str="";
        try {
            System.out.println("userNameinput+pwdinput+LoginApi+apiCodeinput="+userNameinput+pwdinput+LoginApi+apiCodeinput);
            login_res_str = ms.login(userNameinput, pwdinput, LoginApi, apiCodeinput);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(login_res_str)) {
            JSONObject loginJson = JSONObject.fromObject(login_res_str);
            if (loginJson.containsKey("tokenid")) {
                tokenid = loginJson.getString("tokenid");
            } else {
                result ="返回结果异常，无tokenid！结果为：" + login_res_str;
                return  result;
            }
        }
        jso.put("apiName", apiName);
        jso.put("tokenid", tokenid);
        // 传入后台的参数 具体入参 请参考  产品说明字典的传入数据
        reqData.put("id", idCard);
        reqData.put("cell", mobile);//手机
//		reqData.put("bank_id",bankId);
        reqData.put("name", name);
        reqData.put("conf_id", confId);//客户自己选用套餐，可调用多个套餐
        System.out.println("id+cell+bank_id+name+conf_id="+idCard+mobile+bankId+name+confId);
        jso.put("reqData", reqData);
        try {
            result = getBrData(jso.toString(),tokenid,apiCodeinput);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        System.out.println("验证==="+result);
        return  result;
    }
    public static String getstrategyresult( String idCard,String name,String bankId,String mobile,
                                            String userNameinput,  String pwdinput,   String apiCodeinput,
                                            String strategyId,String apiName,String LoginApi){
        String result="";

        JSONObject jso = new JSONObject();
        JSONObject reqData = new JSONObject();
        jso.put("apiName", apiName);
        //获取 登陆验证码，1个小时内使用过，持续有效。
        MerchantServer ms = new MerchantServer();
        String tokenid = "";
        String login_res_str="";
        try {
            login_res_str = ms.login(userNameinput, pwdinput, LoginApi, apiCodeinput);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(login_res_str)) {
            JSONObject loginJson = JSONObject.fromObject(login_res_str);
            if (loginJson.containsKey("tokenid")) {
                tokenid = loginJson.getString("tokenid");
            } else {
                result ="返回结果异常，无tokenid！结果为：" + login_res_str;
                return  result;
            }
        }
        jso.put("tokenid", tokenid);
        // 传入后台的参数 具体入参 请参考  产品说明字典的传入数据
        reqData.put("id", idCard);
        reqData.put("cell", mobile);//手机
//        reqData.put("bank_id",bankId);
        reqData.put("name", name);
        reqData.put("strategy_id", strategyId);//客户自己选用套餐，可调用多个套餐
        jso.put("reqData", reqData);
        System.out.println("id+cell+bank_id+name+conf_id="+idCard+mobile+bankId+name+strategyId);

        try {
            result = getBrData(jso.toString(),tokenid,apiCodeinput);

//            result = ms.getApiData(jso.toString(), apiCodeinput);

        } catch (Exception e) {
//            e.printStackTrace();
        }
        System.out.println("贷前==="+result);
        return  result;
    }
    private static String generateTokenid(String apiCode,String userName,String password){
        String tokenid = "";
        try {
            //登陆
            MerchantServer ms = new MerchantServer();

            String login_res_str = ms.login(userName, password, "LoginApi", apiCode);
            if(StringUtils.isNotBlank(login_res_str)){
                JSONObject loginJson= JSONObject.fromObject(login_res_str);
                if(loginJson.containsKey("tokenid")){
                    tokenid = loginJson.getString("tokenid");
                }else{
                    System.out.println("返回结果异常，无tokenid！结果为："+login_res_str);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return tokenid;
    }

    private static String getCheckData(String jsonData, String apiCode, String tokenId) {
        return MD5Utils.genMd5(jsonData + MD5Utils.genMd5(apiCode + tokenId));
    }

    private static String downloadPdf(String apiCode, String tokenid,String swift_number, String filePath) throws Exception{
        JSONObject jsonData = new JSONObject();
        jsonData.put("swift_number", swift_number);
        String checkCode = getCheckData(jsonData.toString(), apiCode, tokenid);
        String url = "https://api.100credit.cn/query_api/v1/download_approval_report";
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("tokenid", tokenid);
        paramMap.put("apiCode",apiCode);
        paramMap.put("jsonData",jsonData);
        paramMap.put("checkCode",checkCode);
        System.out.println("paramMap->"+paramMap.toString());
        return HttpConnectionManager4.downFile(url, paramMap,filePath);

    }

}
